package yxy.game.pm2.module.passbarrier;

import jodd.util.StringUtil;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import yxy.apple.util.ActiveUtil;
import yxy.apple.util.RandomStringUtility;
import yxy.cherry.battle.Team;
import yxy.cherry.battle.module.Position;
import yxy.cherry.battle.module.record.result.BattleResult;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.passbariercost;
import yxy.cherry.data.bean.tower;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankModule;
import yxy.game.pm2.message.*;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.*;
import yxy.game.pm2.module.hero.FormatHandle;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.niubee.NiuBeeModule;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.tower.TowerHandle;

import java.util.*;

public class PassbarrierHandle {

    // 战斗处理===========================================================================
    private static String code() {
        return BattleType.PASSBARRIER.name();
    }

    /**
     * 封装布阵信息
     *
     * @param playerCode
     * @param module
     * @param response
     * @return
     */
    public Result packFormatInfo(String playerCode, PassbarrierPlayerModule module, PassBarrierMessage.PassBarrierForamtResponse.Builder response) {
        NiuBeeModule niuBeeModule = NiuBeeModule.get(playerCode);
        int progress = niuBeeModule == null ? 0 : niuBeeModule.getProgress();
        int level = niuBeeModule == null ? 0 : niuBeeModule.getLevel();

        response.setNbAct(progress);
        response.setNbLevel(level);
        FormatMessageEntry entry = getFormatInfo(playerCode, module, 0, true);
        response.addAllFormat(entry.getFormats());
        response.addAllHeros(entry.getHeros());
        return Result.Success;
    }

    /**
     * 处理阵容信息返回
     *
     * @param formatNum
     */
    public FormatMessageEntry getFormatInfo(String playerCode, PassbarrierPlayerModule module, int formatNum, boolean isAll) {
        HashMap<String, Hero> heros = new HashMap<>();
        FormatMessageEntry entry = new FormatMessageEntry();

        int i = 0;
        for (Format format : module.getFormats()) {
            FormatMessage.Format.Builder formatBuilder = FormatMessage.Format.newBuilder();

            ArrayList<Hero> formatHeroList = new ArrayList<>();
            Hero herofu = Hero.get(playerCode, format.getFu());
            if (format.getFu() != null && herofu != null) {
                heros.put(herofu.getCode(), herofu);
                formatHeroList.add(herofu);
                formatBuilder.setFU(format.getFu());
            }

            Hero herofm = Hero.get(playerCode, format.getFm());
            if (format.getFm() != null && herofm != null) {
                heros.put(herofm.getCode(), herofm);
                formatHeroList.add(herofm);
                formatBuilder.setFM(format.getFm());
            }

            Hero herofd = Hero.get(playerCode, format.getFd());
            if (format.getFd() != null && herofd != null) {
                heros.put(herofd.getCode(), herofd);
                formatHeroList.add(herofd);
                formatBuilder.setFD(format.getFd());
            }

            Hero herobu = Hero.get(playerCode, format.getBu());
            if (format.getBu() != null && herobu != null) {
                heros.put(herobu.getCode(), herobu);
                formatHeroList.add(herobu);
                formatBuilder.setBU(format.getBu());
            }

            Hero herobm = Hero.get(playerCode, format.getBm());
            if (format.getBm() != null && herobm != null) {
                heros.put(herobm.getCode(), herobm);
                formatHeroList.add(herobm);
                formatBuilder.setBM(format.getBm());
            }

            Hero herobd = Hero.get(playerCode, format.getBd());
            if (format.getBd() != null && herobd != null) {
                heros.put(herobd.getCode(), herobd);
                formatHeroList.add(herobd);
                formatBuilder.setBD(format.getBd());
            }

            formatBuilder.setNB(format.getNb());
            entry.addFormat(formatBuilder.build());

            //从缓存获取
            long totalPower = 0;
            for (Hero hero : formatHeroList) {
                if (hero.getPower() != null) {
                    totalPower += hero.getPower();
                } else {
                    totalPower += new BattleHandle().calculatePower(playerCode, hero, format);
                }
            }

            entry.getFormatPower().add(totalPower);

            if (formatNum > 0 && ++i >= formatNum) {
                break;
            }
        }

        HeroHandle heroHandle = new HeroHandle();
        if (isAll) {
            LinkedList<HeroMessage.HeroSimple> heroSimples = new LinkedList<>();
            for (Hero hero : Hero.all(playerCode).values()) {
                heroSimples.add(heroHandle.getHeroSimple(playerCode, hero));
            }
            entry.addHero(playerCode, heroSimples);

        } else {
            LinkedList<HeroMessage.HeroSimple> heroSimples = new LinkedList<>();
            for (Hero hero : heros.values()) {
                heroSimples.add(heroHandle.getHeroSimple(playerCode, hero));
            }
            entry.addHero(playerCode, heroSimples);
        }
        return entry;
    }


    /**
     * 布阵保存
     *
     * @param playerCode
     * @param formatList
     * @return
     */
    public Result formatSet(String playerCode, List<FormatMessage.Format> formatList, PassbarrierPlayerModule module) {

        if (formatList.size() < 3) {
            return Result.CaptureStrategicPointsFormatLess;// 参战阵容不全
        }

        Map<Integer, Hero> map = new HashMap<>();
        ArrayList<Format> formats = new ArrayList<>();


        for (FormatMessage.Format formatrequest : formatList) {
            Format format = new Format();
            Result result = checkFormat(playerCode, format, null, map, formatrequest);
            if (!result.equals(Result.Success)) {
                return result;
            }
            formats.add(format);
        }

        //保存
        module.getFormats().clear();
        module.getFormats().addAll(formats);
        module.set();
        return Result.Success;

    }


    //检查阵容
    private Result checkFormat(String playerCode, Format format, Map<String, Hero> all, Map<Integer, Hero> map, FormatMessage.Format formatrequest) {
        if (format == null) {
            return Result.DataError;
        }

        FormatHandle formatHandle = new FormatHandle();

        if (!StringUtil.isEmpty(formatrequest.getFU())) {
            format.setFu(formatrequest.getFU());
        }
        if (!StringUtil.isEmpty(formatrequest.getFM())) {
            format.setFm(formatrequest.getFM());
        }
        if (!StringUtil.isEmpty(formatrequest.getFD())) {
            format.setFd(formatrequest.getFD());
        }
        if (!StringUtil.isEmpty(formatrequest.getBU())) {
            format.setBu(formatrequest.getBU());
        }
        if (!StringUtil.isEmpty(formatrequest.getBM())) {
            format.setBm(formatrequest.getBM());
        }
        if (!StringUtil.isEmpty(formatrequest.getBD())) {
            format.setBd(formatrequest.getBD());
        }
        int nb = formatrequest.getNB();
        format.setNb(nb);

        try {
            formatHandle.checkFormat(playerCode, format.getFu(), map);
            formatHandle.checkFormat(playerCode, format.getFm(), map);
            formatHandle.checkFormat(playerCode, format.getFd(), map);
            formatHandle.checkFormat(playerCode, format.getBu(), map);
            formatHandle.checkFormat(playerCode, format.getBm(), map);
            formatHandle.checkFormat(playerCode, format.getBd(), map);
        } catch (Exception e) {
            return Result.FormatSameHero;// 不能上阵同样的武将
        }

        // 检查神器
        if (format.getNb() > 0) {
            NiuBeeModule niubeeModule = NiuBeeModule.get(playerCode);
            if (niubeeModule.getProgress() < format.getNb()) {
                return Result.FormatNiubeeError;// 神器设置错误
            }
        }

        return Result.Success;
    }

    /**
     * 主页信息
     *
     * @param module
     * @return
     */
    public PassBarrierMessage.PassBarrierInfoMsg.Builder getPassBarrierInfo(PassbarrierPlayerModule module) {
        PassBarrierMessage.PassBarrierInfoMsg.Builder builder = PassBarrierMessage.PassBarrierInfoMsg.newBuilder();
        //todo 头部宝箱信息
        for (HeadBox value : module.getHeadBoxMsg().values()) {
            PassBarrierMessage.HeadBox.Builder headBoxMsg = PassBarrierMessage.HeadBox.newBuilder();
            headBoxMsg.setDataId(value.getId());
            headBoxMsg.setIsReward(value.getReward());
            headBoxMsg.setScore(value.getScore());
            builder.addHeadBox(headBoxMsg);
        }
        //todo 怪物信息
        ArrayList<Monster> monsterList = module.getMonsterList();
        for (Monster monster : monsterList) {
            PassBarrierMessage.PassBarrierMonster.Builder monsterMsg = PassBarrierMessage.PassBarrierMonster.newBuilder();
            monsterMsg.setId(monster.getId());
            monsterMsg.setScore(monster.getScore());
            monsterMsg.setIsSuccess(monster.isGothrough());
            monsterMsg.setPower(monster.getTotalPower());
            builder.addMonsterMsg(monsterMsg);
        }
        //todo 当前难度
        builder.setDegree(module.getDegree());
        //todo 剩余挑战次数(初始10次+购买的次数)
        builder.setLessChallengeNum(module.getLessChallengeNum() + module.getChallengePurchaseNum());
        //todo 开始时间 （第二天五点刷新一个轮回）
        DateTime now = DateTime.now();
        builder.setBeginTime(ActiveUtil.time08_00(now).getMillis());
        //todo 结束时间
        builder.setEndTime(ActiveUtil.time22_00(now).getMillis());
        //todo 当前得分
        builder.setScore(module.getTotalScore());
        //todo 历史最高分数
        builder.setMaxScore(module.getPastMaxScore());
        //todo 下次免费刷新的时间戳（重置后第一次该值为null）
        long freeTime = module.getRefreshTime() == null ? 0 : module.getRefreshTime().getMillis();
        builder.setNextRefreshTime(freeTime);
        //todo 剩余免费刷新次数
        builder.setLeftRefreshTimes(module.getLessFreerefreshTimes());
        //todo 挑战次数购买的消耗
        passbariercost data1 = DataCenter.getData(2, passbariercost.class);
        int challengeExtraBuyNum = module.getChallengePurchaseNum() + 1;
        Currency currency1 = Currency.create(data1.getCosttype(), data1.getCostid(), data1.getCostnum() + challengeExtraBuyNum * data1.getExtra());
        PackageMessage.Item fightBuyCost = new CurrencyHandle().packItem(currency1);
        builder.setFightNumCost(fightBuyCost);
        //todo 刷新怪物的消耗
        passbariercost data2 = DataCenter.getData(1, passbariercost.class);
        int refreshExtraBuyNum = module.getRefreshTimes() + 1;
        Currency currency2 = Currency.create(data2.getCosttype(), data2.getCostid(), data2.getCostnum() + refreshExtraBuyNum * data2.getExtra());
        PackageMessage.Item refreshBuyCost = new CurrencyHandle().packItem(currency2);
        builder.setRefreshCost(refreshBuyCost);
        return builder;
    }


    /**
     * 获取战斗记录
     *
     * @param playerCode
     * @param response
     */
    public void record(String playerCode, PassBarrierMessage.PassBarrierRecordResponse.Builder response) {
        List<PassbarrierRecord> records = PassbarrierRecord.get(playerCode);
        for (PassbarrierRecord record : records) {
            PassbarrierRecord.RecordPlayerInfo infoA = record.getInfoA();
            PassbarrierRecord.RecordPlayerInfo infoB = record.getInfoB();
            if (infoA == null || infoB == null) continue;
            PassBarrierMessage.PassBarrierRecord.Builder builder = PassBarrierMessage.PassBarrierRecord.newBuilder();

            builder.setCode(record.getCode());
            builder.setDate(record.getDate().getMillis());
            builder.setWin(record.isWin());
            builder.setDegree(record.getDegree());
            builder.setRank(record.getRank());
            builder.setScore(record.getScore());

            {
                PassBarrierMessage.PassBarrierFighter.Builder fighterA = PassBarrierMessage.PassBarrierFighter.newBuilder();
                fighterA.setNickname(infoA.getPlayerName());//名称
                fighterA.setHead(infoA.getHead());//头像
                fighterA.setHeadFrame(infoA.getHeadFrame());//头像框
                builder.setFighterA(fighterA);
            }

            {
                PassBarrierMessage.PassBarrierFighter.Builder fighterB = PassBarrierMessage.PassBarrierFighter.newBuilder();
                fighterB.setNickname(infoB.getPlayerName());//名称
                fighterB.setHead(infoB.getHead());//头像
                builder.setFighterB(fighterB);
            }

            response.addRecords(builder);
        }
    }

    /**
     * 战斗信息详情
     *
     * @param playerCode
     * @param code
     * @param response
     * @return
     */
    public Result recordInfo(String playerCode, String code, PassBarrierMessage.PassBarrierRecordInfoResponse.Builder response) {
        List<PassbarrierRecord> list = PassbarrierRecord.get(playerCode);
        for (PassbarrierRecord record : list) {
            if (record.getCode().equals(code)) {
                for (String recordCode : record.getRecordCodes()) {
                    BattleRecord battleRecord = BattleRecord.getv(recordCode);
                    if (battleRecord == null) {
                        continue;
                    }
                    response.addPlayback(new BattleHandle().playback(battleRecord));
                }
                return Result.Success;
            }
        }
        return Result.PlainsArenaRecordOut;// 战斗记录不存在了
    }


    /**
     * 封装排行榜信息
     *
     * @param playerCode
     * @param top
     * @param rank
     * @param type
     * @param response
     */
    public void packRank(String playerCode, Collection<RankEntry> top, RankModule rank, int type, PassBarrierMessage.PassBarrierRankResponse.Builder response) {
        PlayerHandle playerHandle = new PlayerHandle();
        int ranking = 0;
        for (RankEntry entry : top) {
            String pCode = entry.getKey();
            int score = entry.getValue().intValue(); //积分

            PassBarrierMessage.RankPassBarrier.Builder builder = PassBarrierMessage.RankPassBarrier.newBuilder();
            builder.setRank(++ranking);
            builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
            builder.setScore(score);

            if (type == PassbarrierRank.currentDayScore) {
                response.addRankForDay(builder);
            } else {
                response.addRankForWeek(builder);
            }
        }

        {
            int playerRank = 0;
            int score = 0;
            RankEntry entry = rank.get(playerCode);
            if (entry != null) {
                playerRank = rank.rank(playerCode);
                score = entry.getValue().intValue();
            }
            PassBarrierMessage.RankPassBarrier.Builder builder = PassBarrierMessage.RankPassBarrier.newBuilder();

            builder.setRank(playerRank);
            builder.setPlayerInfo(playerHandle.playerSimpleInfo(playerCode));
            builder.setScore(score);
            if (type == PassbarrierRank.currentDayScore) {
                response.setDayMyRank(builder);
            } else {
                response.setWeekMyRank(builder);
            }
        }
    }

    /**
     * 战斗主逻辑
     *
     * @param playerCode
     * @param module
     * @param response
     */
    public void battleResponseExecute(String playerCode, PassbarrierPlayerModule module, PassBarrierMessage.PassBarrierChallengeResponse.Builder response) {
        ArrayList<BattleModule> battleList = new ArrayList<>();
        ArrayList<Monster> monsterList = module.getMonsterList();
        LinkedHashMap<String, ArrayList<Monster>> monsterLinkedHashMap = module.getMonsterLinkedHashMap();
        HashMap<String, Integer> passTotalMaxScore = module.getPassTotalMaxScore();
        int totalScore = module.getTotalScore();//当天总分
        int pastMaxScore = module.getPastMaxScore();//历史当次最高分
        int maxScore = module.getMaxScore();//当天当次挑战最高分
        int nowTimeMaxScore = 0;//当次挑战最高分
        int returnScore = 0;//当次挑战获得得积分
        Boolean isBeyond = false;

        int winNum = 0;                             //当前胜利次数
        for (int i = 0; i < monsterList.size(); i++) {
            Monster monster = monsterList.get(i);
            BattleModule battleModule = BattleModule.create(playerCode);
            battleModule.setType(BattleType.PASSBARRIER);
            battleModule.setCode(code());
            battleList.add(battleModule);
            // 玩家的team
            TeamModule teamA = playerTeam(i, module);
            // 怪物的team
            TeamModule teamB = monsterTeam(monster);
            boolean isWin = battleHandle(battleModule, teamA, teamB);
            //胜利
            if (isWin) {
                winNum++;
                nowTimeMaxScore += monster.getScore();
                //首次胜利
                if (!monster.isGothrough()) {
                    totalScore += monster.getScore();
                    returnScore += monster.getScore();
                }
                monster.setGothrough(true);
            }
        }
        //todo 设置当次最高分和总共分数
        module.setTotalScore(totalScore);

        if (nowTimeMaxScore > maxScore) {
            long damage = (nowTimeMaxScore - maxScore);
            module.setMaxScore(nowTimeMaxScore);
            addScore(playerCode, damage);
        }

        if (nowTimeMaxScore > pastMaxScore) {
            module.setPastMaxScore(nowTimeMaxScore);
            isBeyond = true;
        }
        //todo 第一次挑战,不管胜利还是失败都把怪物加入到列表（上限20条），并刷新当前怪物
        if (monsterLinkedHashMap.size() >= PassbarrierPlayerModule.monsterListSize) {
            Iterator<Map.Entry<String, ArrayList<Monster>>> iterator = monsterLinkedHashMap.entrySet().iterator();
            while (iterator.hasNext()) {
                iterator.next();
                iterator.remove();
                break;
            }
        }

        String randomCode = RandomStringUtility.randomLowerNumeric(4);
        monsterLinkedHashMap.put(randomCode, monsterList);
        passTotalMaxScore.put(randomCode, nowTimeMaxScore);
        module.getMonsterByDegree();
        module.setLessChallengeNum(module.getLessChallengeNum() - 1);
        module.set();

        boolean isAllWin = winNum > 0 ? true : false;
        // 处理录像
        ArrayList<BattleRecord> records = new ArrayList<>();
        for (BattleModule battleModule : battleList) {
            if (battleModule.getRecord() == null) {
                continue;
            }
            BattleRecord battleRecord = battleModule.saveRecord(BattleRecord.randomCode(), 1);
            BattleMessage.BattleExecuteResponse.Builder builder = BattleMessage.BattleExecuteResponse.newBuilder();
            builder.setPlayback(new BattleHandle().playback(battleRecord));//
            response.addBattleResp(builder);// 录像
            records.add(battleRecord);
        }

        //保存挑战记录
        addRecord(isAllWin, playerCode, records, monsterList.get(0), nowTimeMaxScore, currentTotalRank(playerCode));
        //返回记录
        for (Monster monster : monsterList) {
            PassBarrierMessage.PassBarrierMonster.Builder monsterMsg = PassBarrierMessage.PassBarrierMonster.newBuilder();
            monsterMsg.setId(monster.getId());
            monsterMsg.setScore(monster.getScore());
            monsterMsg.setIsSuccess(monster.isGothrough());
            monsterMsg.setPower(monster.getTotalPower());
            response.addOldMonsterMsg(monsterMsg);
        }

        response.setWin(isAllWin);//胜利与否
        response.setScore(returnScore);
        response.setIsBeyond(isBeyond);
    }


    /**
     * 再次挑战的战斗主逻辑
     *
     * @param playerCode
     * @param module
     * @param response
     */
    public Result battleAgainResponseExecute(String playerCode, PassbarrierPlayerModule module, PassBarrierMessage.PassBarrierAgainChallengeResponse.Builder response, String code) {
        ArrayList<BattleModule> battleList = new ArrayList<>();
        LinkedHashMap<String, ArrayList<Monster>> monsterLinkedHashMap = module.getMonsterLinkedHashMap();
        int totalScore = module.getTotalScore();    //当天总分
        int pastMaxScore = module.getPastMaxScore();//历史当次最高分
        int maxScore = module.getMaxScore();        //每天最高分
        HashMap<String, Integer> passTotalMaxScore = module.getPassTotalMaxScore();

        //兼容！！
        Integer passTotalScore = passTotalMaxScore.get(code);//当次的历史最高分
        if (passTotalScore == null) passTotalScore = 0;


        //哪三支队伍
        ArrayList<Monster> monsterList = monsterLinkedHashMap.get(code);

        ArrayList<Monster> oldList = new ArrayList<>();
        for (Monster monster : monsterList) {
            Monster old = new Monster();
            old.setGothrough(monster.isGothrough());
            old.setScore(monster.getScore());
            old.setTotalPower(monster.getTotalPower());
            old.setDegree(monster.getDegree());
            old.setId(monster.getId());
            oldList.add(old);
        }

        int winNum = 0;                             //当前胜利次数
        int nowTimeTotalScore = 0;                  //当次挑战的总分
        for (int i = 0; i < monsterList.size(); i++) {
            Monster monster = monsterList.get(i);
            BattleModule battleModule = BattleModule.create(playerCode);
            battleModule.setType(BattleType.PASSBARRIER);
            battleModule.setCode(code());
            battleList.add(battleModule);
            // 玩家的team
            TeamModule teamA = playerTeam(i, module);
            // 怪物的team
            TeamModule teamB = monsterTeam(monster);
            monster.setGothrough(false);
            boolean isWin = battleHandle(battleModule, teamA, teamB);
            if (isWin) {
                winNum++;
                nowTimeTotalScore += monster.getScore();
                monster.setGothrough(true);
            }

        }

        //todo 如果这次的分数比以往的挑战分数高,增加分数，
        if (nowTimeTotalScore > passTotalScore) {

            //设置总共分数
            module.setTotalScore(totalScore + (nowTimeTotalScore - passTotalScore));
            passTotalMaxScore.put(code, passTotalScore + (nowTimeTotalScore - passTotalScore));
            //当天最高分
            if (nowTimeTotalScore > maxScore) {
                //排名分数增加
                addScore(playerCode, (long) (nowTimeTotalScore - maxScore));
                module.setMaxScore(nowTimeTotalScore);
            }
            //设置历史最高分
            if (nowTimeTotalScore > pastMaxScore) {
                module.setPastMaxScore(nowTimeTotalScore);
            }
            module.set();
            response.setScore(nowTimeTotalScore - passTotalScore);
            response.setIsBeyond(true);
            //返回记录
            for (Monster monster : monsterList) {
                PassBarrierMessage.PassBarrierMonster.Builder monsterMsg = PassBarrierMessage.PassBarrierMonster.newBuilder();
                monsterMsg.setId(monster.getId());
                monsterMsg.setScore(monster.getScore());
                monsterMsg.setIsSuccess(monster.isGothrough());
                monsterMsg.setPower(monster.getTotalPower());
                response.addOldMonsterMsg(monsterMsg);
            }
        } else {
            //返回记录
            for (Monster monster : oldList) {
                PassBarrierMessage.PassBarrierMonster.Builder monsterMsg = PassBarrierMessage.PassBarrierMonster.newBuilder();
                monsterMsg.setId(monster.getId());
                monsterMsg.setScore(monster.getScore());
                monsterMsg.setIsSuccess(monster.isGothrough());
                monsterMsg.setPower(monster.getTotalPower());
                response.addOldMonsterMsg(monsterMsg);
            }
        }

        boolean isAllWin = winNum > 0 ? true : false;
        // 处理录像
        ArrayList<BattleRecord> records = new ArrayList<>();
        for (BattleModule battleModule : battleList) {
            if (battleModule.getRecord() == null) {
                continue;
            }
            BattleRecord battleRecord = battleModule.saveRecord(BattleRecord.randomCode(), 1);
            BattleMessage.BattleExecuteResponse.Builder builder = BattleMessage.BattleExecuteResponse.newBuilder();
            builder.setPlayback(new BattleHandle().playback(battleRecord));//
            response.addBattleResp(builder);// 录像
            records.add(battleRecord);
        }

        //保存挑战记录
        addRecord(isAllWin, playerCode, records, monsterList.get(0), nowTimeTotalScore, currentTotalRank(playerCode));

        response.setWin(isAllWin);//胜利与否
        return Result.Success;
    }


    /**
     * 生成战斗结果
     *
     * @param battleModule
     * @param teamA
     * @param teamB
     * @return
     */
    private boolean battleHandle(BattleModule battleModule, TeamModule teamA, TeamModule teamB) {
        if (teamA == null) {
            return false;
        }
        battleModule.setTeamA(teamA);
        if (teamB == null) {
            return true;
        }
        battleModule.setTeamB(teamB);

        BattleHandle battleHandle = new BattleHandle();

        Team team_a = teamA.team(true);
        Team team_b = teamB.team(false);
        team_a.setTeam对手(team_b);
        team_b.setTeam对手(team_a);

        // 处理战斗
        battleHandle.battleExecute(battleModule, team_a, team_b, 20);

        boolean isWin = battleModule.getBattleResult().equals(BattleResult.LEFT_WIN);
        return isWin;
    }


    /**
     * 怪物队伍
     *
     * @param monster
     * @return
     */
    private TeamModule monsterTeam(Monster monster) {
        TeamModule team = new TeamModule();
        TowerHandle towerHandle = new TowerHandle();
        tower _towerdata = DataCenter.getData(monster.getId(), tower.class);
        ArrayList<FighterModule> fighterModules = towerHandle.getFighterModuleList(monster.getId());
        //战力
        long totalPower = 0;
        // 武将
        for (int i = 0; i < _towerdata.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = _towerdata.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            team.addfighter(position, fighterModule);
            totalPower += fighterModule.getTotalPower();
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(_towerdata.getWeapondataid(), _towerdata.getWeaponlv(), 0, 0, _towerdata.getWeaponskilllv());
        team.setWeapon(weapon);
        // 信息
        team.setName("守关武将");
        team.setHead(_towerdata.getHeadid());
        team.setPower(monster.getTotalPower());
        return team;
    }

    /**
     * 玩家队伍
     *
     * @param teamId
     * @param module
     * @return
     */
    private TeamModule playerTeam(int teamId, PassbarrierPlayerModule module) {
        ArrayList<Format> formats = module.getFormats();
        Format format = formats.get(teamId);
        //检查如果武将被吃掉或找不到，删掉
        TeamModule team = new BattleHandle().teamPlayer(module.getPlayerCode(), format);
        return team;
    }

    /**
     * 往排行榜加分数
     *
     * @param playerCode
     * @param damage
     */
    public void addScore(String playerCode, Long damage) {
        PassbarrierRank currentDayRank = PassbarrierRank.getRank(playerCode, PassbarrierRank.currentDayScore);
        PassbarrierRank totalScoreRank = PassbarrierRank.getRank(playerCode, PassbarrierRank.totalScore);
        currentDayRank.addAndSet(playerCode, damage);
        totalScoreRank.addAndSet(playerCode, damage);
    }

    /**
     * 总排行榜上玩家排行
     *
     * @param playerCode
     * @return
     */
    public int currentTotalRank(String playerCode) {
        int playerRank = 0;
        PassbarrierRank rank = PassbarrierRank.getRank(playerCode, PassbarrierRank.totalScore);
        RankEntry entry = rank.get(playerCode);
        if (entry != null) {
            playerRank = rank.rank(playerCode);
        }
        return playerRank;
    }

    /**
     * 添加录像
     *
     * @param isAllWin
     * @param playerCode
     * @param recordList
     * @param monster
     * @param score
     * @param rank
     */
    public void addRecord(Boolean isAllWin, String playerCode, ArrayList<BattleRecord> recordList, Monster monster, int score, int rank) {
        DateTime now = DateTime.now();

        PassbarrierRecord record = new PassbarrierRecord();
        record.setWin(isAllWin);
        PassbarrierRecord.RecordPlayerInfo infoA = new PassbarrierRecord.RecordPlayerInfo();
        PlayerBean playerBean = PlayerBean.get(playerCode);
        infoA.setPlayerName(playerBean.getName());
        infoA.setHead(playerBean.getHead());
        infoA.setHeadFrame(playerBean.getHeadframe());
        record.setInfoA(infoA);

        PassbarrierRecord.RecordPlayerInfo infoB = new PassbarrierRecord.RecordPlayerInfo();
        infoB.setPlayerName("守关武将");
        tower _towerdata = DataCenter.getData(monster.getId(), tower.class);
        infoB.setHead(_towerdata.getHeadid());
        record.setInfoB(infoB);

        for (BattleRecord battleRecord : recordList) {
            record.getRecordCodes().add(battleRecord.getCode());
        }
        record.setDate(now);
        String code = String.format("passbarrierRec%s%s", now.toString(DateTimeFormat.forPattern("yyyyMMddHHmmss")), RandomStringUtility.randomAlpha(4));
        record.setCode(code);
        record.setDegree(monster.getDegree());
        record.setScore(score);
        record.setRank(rank);
        PassbarrierRecord.add(playerCode, record);
    }

    /**
     * 再次挑战里面的怪物信息
     *
     * @param module
     * @param response
     */
    public void info(PassbarrierPlayerModule module, PassBarrierMessage.PassBarrierAgainInfoResponse.Builder response) {
        LinkedHashMap<String, ArrayList<Monster>> map = module.getMonsterLinkedHashMap();
        for (Map.Entry<String, ArrayList<Monster>> entry : map.entrySet()) {
            String key = entry.getKey();
            ArrayList<Monster> value = entry.getValue();
            PassBarrierMessage.PassBarrierAgain.Builder builder = getOneAgainMonsterMsg(key, value);
            response.addInfoList(builder);
        }
    }

    /**
     * 其中三队怪物信息
     *
     * @param key
     * @param value
     * @return
     */
    public PassBarrierMessage.PassBarrierAgain.Builder getOneAgainMonsterMsg(String key, ArrayList<Monster> value) {
        PassBarrierMessage.PassBarrierAgain.Builder builder = PassBarrierMessage.PassBarrierAgain.newBuilder();
        builder.setCode(key);
        builder.setDegree(value.get(0).getDegree());
        for (Monster monster : value) {
            PassBarrierMessage.PassBarrierMonster.Builder monsterMsg = PassBarrierMessage.PassBarrierMonster.newBuilder();
            monsterMsg.setId(monster.getId());
            monsterMsg.setScore(monster.getScore());
            monsterMsg.setIsSuccess(monster.isGothrough());
            monsterMsg.setPower(monster.getTotalPower());
            builder.addMonsterMsg(monsterMsg);
        }
        return builder;
    }


    //内部类------------------------------------------------------------------------------------------------------------
    static private class FormatMessageEntry {
        private ArrayList<FormatMessage.Format> formats;
        private ArrayList<HeroMessage.HeroSimple> heros;
        private ArrayList<Long> formatPower;

        private FormatMessageEntry() {
            formats = new ArrayList<>();
            heros = new ArrayList<>();
            formatPower = new ArrayList<>();
        }

        private ArrayList<FormatMessage.Format> getFormats() {
            return formats;
        }

        private ArrayList<HeroMessage.HeroSimple> getHeros() {
            return heros;
        }

        public ArrayList<Long> getFormatPower() {
            return formatPower;
        }

        public void addFormat(FormatMessage.Format format) {
            formats.add(format);
        }

        private void addHero(String playerCode, LinkedList<HeroMessage.HeroSimple> list) {
            heros.addAll(list);
        }

    }
}
